package com.example.mannortycoon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mannortycoon.dao.UserPointingDao;
import com.example.mannortycoon.entity.SeedEntity;
import com.example.mannortycoon.entity.UserCropEntity;
import com.example.mannortycoon.entity.UserPointingEntity;
import com.example.mannortycoon.entity.UserSeedEntity;
import com.example.mannortycoon.service.SeedService;
import com.example.mannortycoon.service.UserCropService;
import com.example.mannortycoon.service.UserPointingService;
import com.example.mannortycoon.service.UserSeedService;
import com.example.mannortycoon.uitl.R;
import com.example.mannortycoon.vo.UserPointVo;
import io.swagger.models.auth.In;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("userPointingService")
public class UserPointingServiceImpl extends ServiceImpl<UserPointingDao, UserPointingEntity> implements UserPointingService {

    private final SeedService seedService;

    private final UserSeedService userSeedService;

    private final UserCropService userCropService;

    @Autowired
    public UserPointingServiceImpl(SeedService seedService, UserSeedService userSeedService, UserCropService userCropService) {
        this.seedService = seedService;
        this.userSeedService = userSeedService;
        this.userCropService = userCropService;
    }

    @Override
    public List<UserPointingEntity> info(Long id) {
        QueryWrapper<UserPointingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        List<UserPointingEntity> list = this.list(wrapper);
        Map<Integer, UserPointingEntity> map = new HashMap<>();
        list.forEach(item -> map.put(item.getNumber(), item));
        list.clear();
        for (int i = 1; i <= 9; i++) {
            UserPointingEntity userPointingEntity = map.get(i);
            if (userPointingEntity == null) {
                userPointingEntity = new UserPointingEntity();
                userPointingEntity.setUserId(id);
                userPointingEntity.setNumber(i);
            }
            list.add(userPointingEntity);
        }
        return list;
    }

    @Override
    public List<UserPointVo> getUserPointList(Long userId) {
        List<UserPointingEntity> list = this.info(userId);
        return list.stream().map(item -> {
            UserPointVo userPointVo = new UserPointVo();
            userPointVo.setNumber(item.getNumber());
            userPointVo.setSeedId(item.getSeedId());
            SeedEntity seedEntity = seedService.getById(item.getSeedId());
            if (seedEntity != null) {
                userPointVo.setSeedImgUrl(seedEntity.getSeedImgUrl());
                userPointVo.setSeedName(seedEntity.getSeedName());
                userPointVo.setMatureTime(item.getMatureTime());
            }
            return userPointVo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public R userPoint(Long userId, Long seedId, Integer number) {
        //查询用户种子
        QueryWrapper<UserSeedEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("seed_id", seedId);
        UserSeedEntity userSeedEntity = userSeedService.getOne(wrapper);
        if (userSeedEntity == null || userSeedEntity.getNumber() < 1) {
            return R.error("用户种子数量不足");
        }
        //减少用户种子数量
        userSeedEntity.setNumber(userSeedEntity.getNumber() - 1);
        userSeedService.updateById(userSeedEntity);
        //获取用户种植
        QueryWrapper<UserPointingEntity> userPointingEntityQueryWrapper = new QueryWrapper<>();
        userPointingEntityQueryWrapper.eq("user_id",userId).eq("number",number);
        UserPointingEntity userPointingEntity = this.getOne(userPointingEntityQueryWrapper);
        if(userPointingEntity == null){
            userPointingEntity = new UserPointingEntity();
        }
        //修改用户种植列表
        userPointingEntity.setSeedId(seedId);
        userPointingEntity.setUserId(userId);
        userPointingEntity.setPointTime(new Date());
        userPointingEntity.setNumber(number);
        //获取种子信息
        SeedEntity seedEntity= seedService.getById(seedId);
        Integer matureTime = seedEntity.getMatureTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(userPointingEntity.getPointTime());
        calendar.add(Calendar.SECOND, matureTime);
        userPointingEntity.setMatureTime(calendar.getTime());
        this.saveOrUpdate(userPointingEntity);
        return R.ok();
    }

    @Override
    @Transactional
    public void saveUserPointing(Long userId, List<UserPointingEntity> pointList) {
        List<UserPointingEntity> collect = pointList.stream().peek(item -> item.setUpdateTime(new Date())).collect(Collectors.toList());
        this.saveOrUpdateBatch(collect);
    }

    @Override
    @Transactional
    public Integer harvest(Long userId, Integer number) {
        QueryWrapper<UserPointingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("number", number);
        UserPointingEntity userPointingEntity = this.getOne(wrapper);
        if (userPointingEntity == null) {
            return null;
        }
        //获取作物
        SeedEntity seedEntity = seedService.getById(userPointingEntity.getSeedId());
        if (seedEntity == null) {
            return null;
        }
        Long cropId = seedEntity.getCropId();
        //种子的最小收获和最大收获
        Integer minHarvest = seedEntity.getMinHarvest();
        Integer maxHarvest = seedEntity.getMaxHarvest();
        int count = RandomUtils.nextInt(maxHarvest) + minHarvest;
        //获取用户该作物信息
        QueryWrapper<UserCropEntity> userCropEntityQueryWrapper = new QueryWrapper<>();
        userCropEntityQueryWrapper.eq("user_id", userId).eq("crop_id", cropId).eq("is_deleted", 0);
        UserCropEntity userCropEntity = userCropService.getOne(userCropEntityQueryWrapper);
        if (userCropEntity == null) {
            userCropEntity = new UserCropEntity();
            userCropEntity.setCreateTime(new Date());
            userCropEntity.setCropId(cropId);
            userCropEntity.setUserId(userId);
            userCropEntity.setNumber(count);
            userCropService.save(userCropEntity);
        } else {
            userCropEntity.setUpdateTime(new Date());
            userCropEntity.setNumber(userCropEntity.getNumber() + count);
            userCropService.updateById(userCropEntity);
        }
        //更新种植地
        baseMapper.endPointing(userPointingEntity.getId(), new Date());
        return count;
    }
}